//
//  LoginViewController.m
//  UserInfo
//
//  Created by mk on 15/6/12.
//  Copyright (c) 2015年 mk. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
@interface LoginViewController ()
{
    NSPredicate *telPre;
    int keyHeight;
    UITextField * textNow;
    
    int timeM;//倒数秒数
    NSTimer *time;
}

@end

@implementation LoginViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                                object:nil];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [textNow resignFirstResponder];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  //  self.title = @"登录";
    
    viewNavBg.hidden = YES;
    
    telPre  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", isPhoneNumber];
   // [self createView];
    
    txtTel.clearButtonMode = UITextFieldViewModeAlways;
    btnlogin.layer.cornerRadius = 4;
    imageCodebg.layer.cornerRadius = 4;
    imageCodebg.layer.masksToBounds = YES;
    imageTelbg.layer.masksToBounds = YES;
    imageTelbg.layer.cornerRadius = 4;
    [imgBG setImage:[UIImage imageNamed:(iPhone_4)?@"login_bg4.png":@"login_bg5.png"]];
    [scrollMain setAlwaysBounceVertical:YES];
    
}

- (void)backNav:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(IBAction)getCode
{
    if (txtTel.text.length == 0)
    {
        Alert(alerTitle, @"请填写手机号", @"确定")
    }
    else if (![telPre evaluateWithObject:txtTel.text])
    {
        Alert(alerTitle, @"请填写正确的手机号", @"确定")
    }else
    {
      [self requestGode];
    }
}


-(void)requestGode
{
    SetHUDStartText(@"发送验证码..");
    NSString * strUrl = NullObjToString([gProjConfig.dicLocaldata objectForKey:@"sendCodeUrl"]);// loginUrl
   // strUrl = [NSString stringWithFormat:@"%@?os=ios&appv=15&api=4",strUrl];
   // NSLog(@"requestGode==%@",strUrl);
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dic setObject:txtTel.text forKey:@"smsVerifyCode[mobile]"];
    [dic setObject:@"102" forKey:@"smsVerifyCode[action_type]"];
    
    [[HttpClient manager]POST:strUrl
                   parameters:dic
     
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
         timeM = 60;
         SetHUDFinishedText(@"已经发送到您的手机")

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view)
    }];
}



-(void)timerFired
{
    timeM = timeM - 1;
    if (timeM == 0)
    {
        [time invalidate];
        
        [btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        btnCode.userInteractionEnabled = YES;
    }
    else
    {
        [btnCode setTitle:[NSString stringWithFormat:@"%ds",timeM] forState:UIControlStateNormal];
        btnCode.userInteractionEnabled = NO;
    }
}



- (IBAction)loginButton:(UIButton *)button
{
    if (txtTel.text.length == 0 || txtCode.text.length == 0)
    {
        Alert(alerTitle, @"请填写手机号或验证码", @"确定")
    }
    else if (![telPre evaluateWithObject:txtTel.text])
    {
      Alert(alerTitle, @"请填写正确的手机号", @"确定")
    }
  
    else{

      SetHUDStartText(@"登录中..");
        
    NSString * strUrl = NullObjToString([gProjConfig.dicLocaldata objectForKey:@"loginUrl"]);
    //strUrl = [NSString stringWithFormat:@"%@?os=ios&appv=15&api=4",strUrl];
        
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dic setObject:txtTel.text forKey:@"userLogin[username]"];
    [dic setObject:txtCode.text forKey:@"userLogin[verify_code]"];

    [[HttpClient manager]POST:strUrl
                                 parameters:dic
          success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            SetHUDHidden;
            NSString * token = [[responseObject objectForKey:requestDataKey] objectForKey:@"token"];
           // NSLog(@"==%@===%@",token,responseObject);
            [gProjConfig.dicUserData removeAllObjects];
            [gProjConfig.dicUserData setObject:token forKey:USER_token];
            [gProjConfig.dicUserData setObject:txtTel.text forKey:USER_tel];
            [gProjConfig writeToFile];
            if ([self.detegate respondsToSelector:@selector(loginSuccess)])
            {
                [self.detegate loginSuccess];
            }
            [self dismissViewControllerAnimated:YES completion:^{}];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            SetHUDHidden;
           HUDShowRequestError(error.domain, self.view)
        }];
        
    }
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    if (textField == txtTel)
//    {
//        [txtCode becomeFirstResponder];
//        return YES;
//    }
    [textField resignFirstResponder];
    return YES;
}

#pragma mark textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    textNow = textField;
    [self changeViewFrame];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
}


#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
    bottomDistance = appScreenHeight - (64 + textNow.bottom);//键盘预留高度
    int content = (keyHeight + 30) - bottomDistance;
    if (content>0)
    {
        [scrollMain setContentOffset:CGPointMake(0,content) animated:YES];
    }

}

//
//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    [textNow resignFirstResponder];
//}

//-(void)textfieldContentWithoutAnimate:(NSLayoutConstraint *)constraint
//{
//    [UIView animateWithDuration:0.2 animations:^{
//        
//        [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
//        
//    }];
//}


//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
//{
//    DLog(@"====%f",scrollMain.contentOffset.y);
//}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [textNow resignFirstResponder];
}



//

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end





